<template>
  <el-select v-model="selectedUserId" filterable :placeholder="placeholder" @change="handleNodeChange" clearable>
    <el-option
      v-for="item in userList"
      :key="item.id"
      :label="item.nickname"
      :value="item.id" />
  </el-select>
</template>
<script lang="ts" setup>
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'PostUserSelect' })

const { t } = useI18n() // 国际化

const props = defineProps({
  userId: {
    type: Number,
    default: undefined,
  },
  postId: {
    type: Number,
    default: undefined,
  },
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const selectedUserId = ref(props.userId || undefined)
const userList = ref<UserApi.UserVO[]>([])

const getList = async() => {
  if (!props.postId) {
    userList.value = []
    return
  }
  const list = await UserApi.getSimpleUserListByPostId(props.postId)
  userList.value = list
}

/** 处理员工选择 */
const handleNodeChange = async (item: number|any) => {
  if (!item || item === 0 || item === undefined) {
    emits('node-change', null)
    return
  }
  const info = userList.value.find(i=>i.id==item)
  emits('node-change', info)
}
const emits = defineEmits(['node-change'])

/** 监听userId变化 */
watch(() => props.userId, (newVal) => {
  selectedUserId.value = newVal || undefined
})

/** 监听postId变化 */
watch(() => props.postId, (newVal) => {
  if (newVal) {
    getList()
  } else {
    userList.value = []
  }
  // 清空选择
  selectedUserId.value = undefined
  emits('node-change', null)
})

/** 初始化 */
onMounted(() => {
  if (props.postId) {
    getList()
  }
})
</script> 